//
//  PaperViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/29.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import SnapKit
import IQKeyboardManagerSwift
import Async

class PaperViewController: ViewController, LeftBarButtonItemable {
    
    ///保存最近一次试卷
    static var lastPaperVC: PaperViewController? = nil
    ///进入试卷，如果跟上一次试卷相同，直接进入上次的试题
    static func startPaper(_ paperId: Int,
                           paper: PaperModel? = nil,
                           status: PaperStatus,
                           title: String? = nil,
                           pUserSummaryId: Int? = nil) -> PaperViewController {
        if let lastPaperVC = PaperViewController.lastPaperVC {
            if lastPaperVC.vm.paperId == paperId &&
                lastPaperVC.vm.status == status {
                return lastPaperVC
            }
        }
        
        let paperVC = PaperViewController.init(paperId,
                                               paper: paper,
                                               status: status,
                                               title: title,
                                               pUserSummaryId: pUserSummaryId)
        PaperViewController.lastPaperVC = paperVC
        return paperVC
    }

    //view model
    var vm: PaperViewModel!
    
    //view
    private var pageController:UIPageViewController?
    private var panelView: PaperBasePanelView?

    
    /// 试卷页面
    ///
    /// - Parameters:
    ///   - paperId: 试卷id
    ///   - paper: 试卷详情
    ///   - status: 试卷类型
    ///   - title: 标题
    ///   - pUserSummaryId: 错题试卷详情需要
    init(_ paperId: Int,
         paper: PaperModel? = nil,
         status: PaperStatus,
         title: String? = nil,
         pUserSummaryId: Int? = nil) {
        self.vm = PaperViewModel.init(paperId, paper: paper, status: status, pUserSummaryId: pUserSummaryId, title: title)
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        setLeftItem()
     
        bindUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setPopRecognizerEnable(false)
        IQKeyboardManager.sharedManager().enable = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(false)
    }
    
    func bindUI() {
        
        vm.vmData.asObservable().bind {[weak self] (paper) in
            self?.setupPaper()
            }.disposed(by: disposeBag)
        
        //监听index变化
        vm.index.asObservable().bind { [weak self] (idx) in
            self?.panelView?.index = idx
            
            //是否需要提醒购买
            self?.alertBuy()
            }.disposed(by: disposeBag)
        
        //获取试卷详情
        vm.paperListCommand.onNext(vm.status)
    }
}



// MARK:-
// MARK: UI
extension PaperViewController {
    
    private func setupPaper() {
        //清除UI
        cleanUI()
        
        guard let count = vm.paper?.paperItems?.count else {
            return
        }
        if count <= 0 { return }
        
        initUI()
        
        guard let vc = paperItemController(0) else { return }
        vm.index.value = 0
        reloadPageController(vc: vc, direction: .forward, animated: false)
    }
    
    ///清空UI
    private func cleanUI() {
        pageController?.view.removeFromSuperview()
        pageController?.removeFromParentViewController()
        pageController = nil
        
        panelView?.removeFromSuperview()
        panelView = nil
        
        navigationItem.rightBarButtonItem = nil
    }
    
    ///获取试卷成功后再加载UI 
    private func initUI() {
     
        initPageController()
        initPanelView()
        initNavigationItem()
        
    }
    
    func initPageController() {
        let pageController = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageController.delegate = self
        pageController.dataSource = self
        view.addSubview(pageController.view)
        addChildViewController(pageController)
        
        pageController.view.snp.makeConstraints { (maker) in
            maker.leading.trailing.top.equalToSuperview()
        }
        self.pageController = pageController
    }
    
    func initPanelView() {
       
        var panelView: PaperBasePanelView
        
        ///题卡，交卷按钮
        if vm.paper?.method == .exam {
            panelView = PaperExamPanelView()
        }
        ///练习模式
        else {
            switch vm.status {
                //查看解析模式， 不显示按钮
            case .analysis, .record:
                panelView = PaperAnalysisPanelView()
                
                //自评分模式，提交评分按钮
            case .selfReported:
                let selfReportView = PaperSelfReportPanelView()
                selfReportView.selfReportHandle = { [weak self] in
                    self?.selfReportClick()
                }
                panelView = selfReportView
                break
            /// 题卡、解析按钮
            default:
                let panel = PaperExamPanelView()
                panel.submitBtn.setTitle("解析", for: .normal)
                panelView = panel
            }
        }
        
        panelView.total = vm.paper?.paperItems?.count
        view.addSubview(panelView)
        panelView.snp.makeConstraints { (maker) in
            maker.leading.trailing.equalToSuperview()
            maker.height.equalTo(80)
            maker.top.equalTo((pageController?.view.snp.bottom)!)
            maker.bottom.equalToSuperview().offset(0 - safeAreaInsets().bottom)
        }
        
        panelView.forwardHandle = {
            self.forward()
        }
        
        panelView.reverseHandle = {
            self.reverse()
        }
        
        panelView.submitHandle = {
            self.submitPaper()
        }
        
        panelView.cardHandle = {
            self.cardClick()
        }
        self.panelView = panelView
    }
    
    ///初始化更多按钮
    func initNavigationItem() {
        let barItem = UIBarButtonItem.init()
        barItem.tintColor = UIColor.white
        barItem.image = UIImage.init(named: "Icon more")
        barItem.style = .plain
        
        barItem.rx.tap.bind { [weak self] in
    
            self?.moreClick()
        }.disposed(by: disposeBag)
        
        navigationItem.rightBarButtonItem = barItem
        
        let titleLabel = UILabel.init().then { (label) in
            label.textColor = UIColor.white
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 17)
            label.text = self.vm.title
        }
        navigationItem.titleView = titleLabel
    }
  
    
    ///获取当前显示的页面
    func currentItemController() -> PaperItemViewController? {
        return  pageController?.viewControllers?.first as? PaperItemViewController
    }
    
    ///重复reload，修复代理方法没有刷新的bug
    func reloadPageController(vc: UIViewController, direction: UIPageViewControllerNavigationDirection = .forward, animated: Bool = false) {
        self.pageController?.setViewControllers([vc], direction: direction, animated: animated, completion: { (finished) in
            DispatchQueue.main.async { [weak self] in
                self?.pageController?.setViewControllers([vc], direction: direction, animated: false, completion: nil)
            }
        })
    }
    
}

// MARK:-
// MARK: 用户交互
extension PaperViewController {
    
    
    ///点击更多
    private func moreClick() {
        
        let itemVC = currentItemController()
        guard let item = itemVC?.paperItem else { return }
        
        var likeStr = "收藏"
        if item.userLike == .like {
            likeStr = "取消收藏"
        }
        
        lsf_alert(style: .actionSheet,
                  viewController: self,
                  actionTitles: [likeStr],
                  cancelTitle: "取消",
                  sourceView: view) { [weak self] (title) in
                    
                    if title == "收藏" {
                        self?.vm.likeCommand.onNext((item, 1))
                    }
                        
                    else if title == "取消收藏" {
                        self?.vm.likeCommand.onNext((item, 0))
                    }
        }
    }
    
    func paperItemController(_ index:Int) -> UIViewController? {
        if index < 0 {
            return nil
        }
        guard let total = vm.paper?.paperItems?.count else {
            return nil
        }
        if total <= index {
            //            alertBuy()
            return nil
        }
        
        guard let paperItem = vm.paper?.paperItems?[index] else { return nil }
        let paperItemVC = PaperItemViewController.init(paperItem, index:index)
        
        
        paperItemVC.selectComplete = { paperItem in
            if paperItem.type == .radio || paperItem.type == .trueOrFalse {
                
                //如果是练习模式，并且答案错误的话，显示解析
                if self.vm.paper?.method != .exam,
                    paperItem.userAnswer != paperItem.answer {
                    
                    paperItem.method = .analysis
                    paperItemVC.reload()
                    
                    ///去掉自动进入下一题，改为手动
//                    Async.main(after: 1, { [weak self] in
//                        //下一题
//                        self?.forward()
//                    })
                }
                else {
                    //下一题
                    self.forward()
                }
                
            }
        }
        
        return paperItemVC
    }
    
    //如果是试用模式，提示购买试卷
    func alertBuy()  {
        if vm.status == .trial {
            guard let total = vm.paper?.paperItems?.count else {
                return
            }
            if vm.index.value < total - 1 {
                return
            }
            
            let price = vm.paper?.price ?? 0
            let alert = RechargeAlert.init(paperId: vm.paperId, price: price, presentController:self, compelete: { [weak self] (result) in
                if result {
                    //支付成功，重新获取试卷列表
                    self?.vm.status = .bought
                    //清空UI
                    self?.cleanUI()
                    //获取试卷详情
                    self?.vm.paperListCommand.onNext((self?.vm.status)!)
                }
            })
            alert.show()
        }
    }
    
    ///下一题
    func forward() {
        guard let currentVC = pageController?.viewControllers?.first as? PaperItemViewController else { return }
        
        //保存当前题目的答案
        currentVC.saveAnswer()
        
        var idx = currentVC.index
        idx = idx + 1
        guard let nextVC = paperItemController(idx) else { return }
        
        vm.index.value = idx
        //显示新的页面
        reloadPageController(vc: nextVC, direction: .forward, animated: true)
    }
    
    ///上一题
    func reverse() {
        
        guard let currentVC = pageController?.viewControllers?.first as? PaperItemViewController else { return }
        
         //保存当前题目的答案
        currentVC.saveAnswer()
        
        var idx = currentVC.index
        idx = idx - 1
        guard let nextVC = paperItemController(idx) else { return }
        
        vm.index.value = idx
        //显示新的页面
        reloadPageController(vc: nextVC, direction: .reverse, animated: true)
    }
    
    ///交卷/解析
    func submitPaper() {
        
        guard let itemVC = currentItemController() else { return }
        
        //保存当前题目的答案
        itemVC.saveAnswer()
   
        //考试模式，提交试卷
        if vm.paper?.method == .exam {
            submit(completeHanlde: { [weak self] (model) in
                
                ///交卷之后,不在保留最后一套试题
                PaperViewController.lastPaperVC = nil
                
                if let paper = model {
                    let reportVC = PaperReportViewController.init(paper)
                    ///重考
                    reportVC.reExamHandle = { [weak self] in
                        ///清除UI
                        self?.cleanUI()
                        ///重新获取试题
                        self?.navigationController?.popViewController(animated: true)
                        self?.vm.reEaxm()
                    }
                    self?.navigationController?.pushViewController(reportVC, animated: true)
                }
            })
        }
        else {
            
            //练习模式，显示答案解析
            itemVC.paperItem.method = .analysis
            itemVC.reload()
        }
    }
    
    ///交卷
    func submit(completeHanlde: ((PaperModel?)->Void)?) {
        lsf_alert("要不要再检查一遍后提交？", viewController: self, cancelTitle: "再检查一遍", destructiveTitle: "确认交卷", handle: { [weak self] (title) in
            if title == "确认交卷" {
                //交卷
                self?.vm.submit({ (model) in
                    completeHanlde?(model)
                })
            }
        })
    }
    
    ///点击题卡
    func cardClick() {
        
        guard let paper = self.vm.paper else { return }
        let cardVC = PaperCardViewController.init(paper)
        cardVC.selectHandle = { [weak self] item in
            if let index = self?.vm.paper?.paperItems?.index(where: {$0.id == item.id }) {
                guard let vc = self?.paperItemController(index) else { return }
                self?.vm.index.value = index
                //显示新的页面
                self?.reloadPageController(vc: vc, direction: .forward, animated: false)
            }
        }
        ///交卷
        cardVC.submitHandle = { [weak self] in
            self?.submit(completeHanlde: { [weak self] (paper) in
                self?.navigationController?.popViewController(animated: false)
                if let paper = paper {
                    paper.title = self?.title
                    let reportVC = PaperReportViewController.init(paper)
                    self?.navigationController?.pushViewController(reportVC, animated: true)
                }
            })
        }
        navigationController?.pushViewController(cardVC, animated: true)
    }
    
    ///自评分
    func selfReportClick() {
        lsf_alert("要不要再检查一遍后提交？", viewController: self, cancelTitle: "再检查一遍", destructiveTitle: "提交", handle: { [weak self] (title) in
            if title == "提交" {
                //自评分
                self?.vm.selfReport({ [weak self] in
                    self?.navigationController?.popViewController(animated: true)
                    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: PaperReportCompleteNotification), object: nil)
                })
            }
        })
    }
}

extension PaperViewController: UIPageViewControllerDataSource {
    
    ///上一页
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        let paperItemVC = viewController as! PaperItemViewController
        var idx = paperItemVC.index
        
        idx = idx - 1
        return paperItemController(idx)
    }
    
    ///下一页
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let paperItemVC = viewController as! PaperItemViewController
        var idx = paperItemVC.index
        
        idx = idx + 1
        return paperItemController(idx)
    }
}

extension PaperViewController: UIPageViewControllerDelegate {
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        // true表示手势滑动翻页成功， false表示滑动一半取消滑动
        if completed {
            //滑动前题目
            if let previousVC = previousViewControllers.first as? PaperItemViewController{
                previousVC.saveAnswer()
            }
            
            //滑动后当前题目
            if let itemVC = pageViewController.viewControllers?.first as? PaperItemViewController {
                let idx = itemVC.index
                vm.index.value = idx
            }
        }
    }
}

